﻿/// <reference path="../../jQuery/jquery.js"/>
/// <reference path="../../jQuery/jquery-calendar.js"/>
/// <reference path="../../jQuery/jquery.autocomplete.js"/>
/// <reference path="../../jQuery/jquery.autoloadselect.js"/>
/// <reference path="../../jQuery/jquery.wizard.js"/>
/// <reference path="../../json2.js"/>

var j=jQuery.noConflict();

jQuery(function ($) {
	var ListOfPerfs = [];
	var changed = false;

	$("#frmWizard").show();
	$("#waiting").hide();

	$('#hypEditTroupe').disable();
	$(".coolbutton").button();

	// tabs-Productions  ===========================================================================================
	$('#TroupeId').selectChain({ target: '#season', url: siteRoot + '/Admin/SeasonsJson.rails' });
	$('#TroupeId').selectChain({ target: '#cbxStandard', url: siteRoot + '/Admin/SchedulesJson.rails' });
	$('#TroupeId').bind("change", function () {
		$("#frmWizard").wizard("enableNext");
		$("#hypEditTroupe").enable();
	});

	$('#season').bind("change", function () { ShowProdsGrid($('#season').val()); changed = false; });
	$("#dialogDelete").dialog({
		resizable: false,
		autoOpen: false,
		height: 250,
		width: 500,
		modal: true,
		overlay:
				{
					backgroundColor: '#000',
					opacity: 0.5
				},
		buttons:
			{
				"Yes- Delete it.": function () {
					j.ajax({
						url: siteRoot + "/Show/DeleteJson.rails",
						data: { id: $('#ProductionId').val() },
						dataType: 'json',
						success: function () {
							$('#tblProductions').trigger("reloadGrid");
							//jQuery.growl('Production deleted', 'Production deleted');
							$('#StatusBar').jnotifyAddMessage({
								text: 'Production deleted',
								permanent: false,
								type: 'message'
							});
						}
					});
					$(this).dialog('close');
				},
				"No - Cancel": function () {
					$(this).dialog('close');
				}
			}
	});

	$('#btnDeleteProd').click(function () {
		$('#dialogDelete')
		.text("This will completely DELETE '{0}'.  Are you absolutely SURE?".format($('#txtPlay').val()))
		.dialog('open');
	}).disable();

	$('#btnAddProd').click(function () {
		$('#ProductionId').val(0);
		$('#VenueId').val(0);
		$('#txtPlay').val('');
		$('#PlayId').val(0);
		$('#txtAuthors').html('');
		$("#playComments").val('');
		$('.date-pick').val('');
		$("#frmWizard").wizard('gotoStep', '#tabs-Play');
		changed = true;
	});

	// tabs-Options ===========================================================================================
	$("#btnContinue, #btnContinue2").click(function () {
		$("#frmWizard").wizard("moveNext");
		return false;
	});

	$('.restart').click(function () { $("#frmWizard").wizard('gotoStep', '#tabs-Productions'); });


	// tabs-Venues ===========================================================================================
	$('#lstCounties').selectChain({ target: '#lstVenues', url: siteRoot + '/Venue/ForCountyJson.rails' })
								.hide().bind("change", function () {
									$('#lstVenues').show();
									changed = true;
								});

	$('#lstVenues').hide().bind("change", function () {
		SelectVenue($(this));
		changed = true;
	});
	$('#cbxOwnVenues').bind("change", function (event, fromCode) {
		var elm = $(this);
		if (elm.val() > '') {
			if (elm.val() == "0") {
				$('#lstCounties').show(); $('#lstVenues').show();
				$("#frmWizard").wizard("disableNext");
				$('#venueInfo').html("<td style='width:600px; height:59px;' ></td><td></td>");
			}
			else { $('#lstCounties').hide(); $('#lstVenues').hide(); SelectVenue(elm); }

			if (!fromCode)
				changed = true;
		}
	});

	// tabs-Play ===========================================================================================
	$("#dialogCreatePlay").dialog({
		resizable: false,
		autoOpen: false,
		height: 250,
		modal: true,
		overlay: { backgroundColor: '#000', opacity: 0.5 },
		buttons:
			{
				'Yes- Create it.': function () {
					$(this).dialog('close');
					$('#playComments').popupeditor({ length: 2000, title: $("#txtPlay").val(),
						onSave: function () {
							j.ajax({
								url: siteRoot + '/Play/AddJson.rails',
								data: { title: $("#txtPlay").val(), comments: $('#playComments').val() },
								dataType: 'json',
								type: 'POST',
								success: function (data, textStatus) {
									$('#PlayId').val(data);
									$("#NewPlayNotice").show();
									$('#txtAuthors').text("New Play info saved.  Be sure to use the CastList feature to add playwright");
									$('#StatusBar').jnotifyAddMessage({
										text: "Play '" + $("#txtPlay").val() + "' has been created",
										permanent: false,
										type: 'message'
									});

								}
							});
						}
					});

				},
				'No - Cancel': function () {
					$(this).dialog('close');
				}
			}
	});

	$("#txtPlay").autocomplete(
		{
			source: AutoCompleteSource,
			url: siteRoot + "/Play/FindPlaysText.rails",
			width: 500,
			mustMatch: false,
			autoFill: false,
			selectFirst: false,
			type: 'text',
			formatItem: function (row, pos, num, term) {
				var maxDesc = 84;
				var desc = (row[2].length > maxDesc) ? row[2].substr(0, maxDesc) + '...' : row[2];
				$('#PlayId').val("0");
				return row[1] + '<br/>(' + row[3] + ')<br/><i>' + desc + '</i>';
				//				return row[1] + '\n(' + row[3] + ')\n' + desc;
			},
			formatResult: function (data, value) {
				return data[1];
			},
			select: function (event, data, formatted) {
				//				$("#txtCounter").text('S');
				// called if selection from list
				$("#PlayId").val(data.item.id);
				$('#txtAuthors').html(data.item.item[3]);
				$("#playComments").attr('readonly', false).val(data.item.item[2]).attr('readonly', true)

				changed = true;
				$("#frmWizard").wizard("enableNext");
			}
		})
	.bind("nomatch.autocomplete", function () {
	})
	.blur(function () {
		if ($('#PlayId').val() > "0") {
			$("#NewPlayNotice").hide();
			if ($('#txtAuthors').html() == "")
				$("#NewPlayNotice").show();
		}
		else {
			setTimeout(function () {   // blur may come before or after the select event, so we have to delay this.
				if ($('#PlayId').val() == "0")  // If still 0 after a second, then try to create
				{
					$('#dialogCreatePlay')
					.text("This will create a new play called '{0}'.  Are you SURE?".format($('#txtPlay').val()))
					.dialog('open');
				}
			}, 1000);
		}
		$("#frmWizard").wizard("enableNext");
	});
	$('#playComments').click(function () {
		$('#playComments').popupeditor({ length: 2000, title: $("#txtPlay").val(),
			onSave: function () {
				j.ajax({
					url: siteRoot + '/Play/UpdateComment.rails',
					data: { id: $("#PlayId").val(), comments: $('#playComments').val() },
					dataType: 'json',
					type: 'POST',
					success: function (data, textStatus) {
						$('#StatusBar').jnotifyAddMessage({
							text: "Comment for " + $("#txtPlay").val() + " has been updated",
							permanent: false,
							type: 'message'
						});
					}
				});
			}
		});
	});


	// tabs-Dates  ===========================================================================================
	$(".date-pick").datepicker(
			{
				showOn: 'both',
				buttonImageOnly: false,
				buttonText: '...'
			});

	$('#FirstPerformance').datepicker('option', 'onSelect', function () {
		var last = $('#LastPerformance');
		last.datepicker('option', 'minDate', $(this).datepicker('getDate'));
		last.datepicker('enable');
		changed = true;
	});

	var last = $('#LastPerformance');
	last.datepicker('option', 'onSelect', function () {
		changed = true;
		$("#frmWizard").wizard("enableNext");
	});

	$('#txtComments').click(function (evnt) {
		$('#txtComments').popupeditor({ length: 1000, title: "Production notes",
			onSave: function () { changed = true; }
		});
	});

	// tabs-SaveProduction==========================================================================================
	$('#btnSaveProd').click(function (event) {
		$('#btnSaveProd').disable();
		j.ajax({
			url: siteRoot + '/Show/EditDetails.rails',
			data: { id: $('#ProductionId').val(), troupeid: $('#TroupeId').val(),
				venueid: $('#VenueId').val(), playid: $('#PlayId').val(),
				start: $('#FirstPerformance').val(), end: $('#LastPerformance').val(), comments: $('#txtComments').val()
			},
			dataType: 'json',
			type: 'POST',
			success: function (data, textStatus) {
				if (data.ID == 0) {
					$('#btnSaveProd').enable();
					$('#StatusBar').jnotifyAddMessage({
						text: 'An error Occured: ' + data.Title,
						permanent: true,
						type: 'error'
					});

				}
				else {
					$('#StatusBar').jnotifyAddMessage({
						text: 'Production ' + data.Title + ' has been saved.  Click [Next] to add performance times',
						permanent: false,
						type: 'message'
					});

					changed = false;
					$('#ProductionId').val(data.ID);
				}
			}
		});
		$("#frmWizard").wizard('enableNext');
		return false;
	});

	$(".btnCancel").click(function () {
		$("#frmWizard").wizard('gotoStep', 0);
		return false;
	});

	// tabs-Performances  ===========================================================================================
	$('#btnAddPerfs').click(function (event) {
		var currDate = new Date($('#FirstPerformance').val());
		currDate.addDays(($('#ddlDay').val() - currDate.getDay() + 7) % 7);
		var lastDate = new Date($('#LastPerformance').val());
		var time = $('#ddlTime').val();
		var newDates = [];
		while (currDate <= lastDate) {
			var newDate = new Date(currDate.getTime());
			newDates.push({ Date: newDate, Title: time, URL: '#' });
			currDate.addDays(7);
		}
		$.jMonthCalendar.AddEvents(newDates);
	});

	$('#btnInsert').click(function (event) {
		$.getJSON(siteRoot + '/Show/GetSchedulePerfsJson.rails', { ProductionId: $('#ProductionId').val(), SchedId: $('#cbxStandard').val() },
							function (data, textStatus) {
								$.jMonthCalendar.AddEvents(data);
							}
						);
	});

	$("#btnSave").click(function (event)     // save Performaces
	{
		ListOfPerfs = _.select(ListOfPerfs, function (obj) { return !(obj instanceof Array && obj.length == 0); });
		var jsontext = JSON.stringify(ListOfPerfs);
		$.post(siteRoot + '/Show/SavePerfsJson.rails',
							{ ProductionId: $('#ProductionId').val(), Dates: jsontext },
							function (data, textStatus) {
								//							    jQuery.growl("Success", 'Performance Dates saved.');
								$('#StatusBar').jnotifyAddMessage({
									text: 'Performance Dates saved.',
									permanent: false,
									type: 'message'
								});

							},
							"json"
						);
	});

	$('#btnClear').click(function (event) {
		ListOfPerfs = [];
		$.jMonthCalendar.ReplaceEventCollection(ListOfPerfs);
		$.jMonthCalendar.AddEvents([]);
	});

	$(".AddProdId").click(function () {
		var href = $(this).attr("href") + "?id=" + $("#ProductionId").val();
		window.location = href;
		return false;
	});

	$(".AddTroupeId").click(function () {
		var href = $(this).attr("href") + "?id=" + $("#TroupeId").val();
		window.location = href;
		return false;
	});


	$("#frmWizard").wizard({ show: PreparePanel,
		historyEnabled: false,
		formPluginEnabled: true,
		validationEnabled: false
	});

	StartExact($);

	function PreparePanel(event, ui) {
		var element = ui.step[0];
		if (element == null)
			return;

		switch (element.id) {
			case 'tabs-Troupe':
				$("#hypEditTroupe").disable();
				var troupes = $("#TroupeId  option");
				if (troupes.length == 1) {
					troupes[0].selected = true;
					$('#TroupeId').disable();
				}
				if (troupes.anySelected()) {
					$("#frmWizard").wizard("enableNext");
					$("#hypEditTroupe").enable();
					$("#TroupeId").change();
				}
				break;

			case 'tabs-Productions':
				break;

			case 'tabs-Venue':
				$('#cbxOwnVenues')
					.autoloadSelect(
								{
									url: siteRoot + '/Venue/VenuesForProduction.rails',
									data: { TroupeID: $('#TroupeId').val(), ProductionID: $('#ProductionId').val() }
								})
					 .trigger("change");
				break;

			case 'tabs-Play':
				if ($('#PlayId').val() > '0') {
					$.get(siteRoot + '/Play/InfoJson.rails', { PlayId: $('#PlayId').val() }, function (data) {
						$('#txtAuthors').html(data.Credits);
						$('#playComments').val(data.Comments);
						$("#frmWizard").wizard("enableNext");
					}, "json");
				}
				$('#txtPlay').focus();
				break;

			case 'tabs-Dates':
				if ($('#FirstPerformance').val() == '')
					$('#LastPerformance').datepicker('disable');
				else
					$('#LastPerformance').datepicker('enable');

				if ($('#LastPerformance').val() > '')
					$("#frmWizard").wizard("enableNext");
				else
					$("#frmWizard").wizard("disableNext");
				break;

			case 'tabs-SaveProduction':
				if (changed) {
					$("#lblSave").show();
					$("#lblNoChanges").hide();
					$("#btnSaveProd").enable();
				}
				else {
					$("#lblSave").hide();
					$("#lblNoChanges").show();
					$("#btnSaveProd").disable();
					$("#frmWizard").wizard("enableNext");
				}
				break;

			case 'tabs-Performances':
				$("#frmWizard").wizard("enableNext");
				$.getJSON(siteRoot + '/Show/GetPerfsJson.rails', { ProductionId: $('#ProductionId').val() },
							function (data, textStatus) {
								var start = data.length > 0 ? data[0].Date : new Date($('#FirstPerformance').val());
								$.jMonthCalendar.Initialize(
								{
									calendarStartDate: start,
									width: 800,
									height: 400,
									onEventLinkClick: function (evnt) {
										var e = evnt;
										var newPerfs = _.select(ListOfPerfs, function (dat) {
											return dat.Date != evnt.Date;
										});
										ListOfPerfs = newPerfs;
										$.jMonthCalendar.ReplaceEventCollection(ListOfPerfs);
										$.jMonthCalendar.AddEvents([]);
										return false;
										// delete current event
									},
									onDayCellDblClick: function (date, cell) {
										if (cell.data("active") === date)
											return false;
										cell.data("active", date);
										var ddl = $('#ddlTime').clone();
										ddl.prepend("<option value=' ' selected='selected'></option>");
										ddl.val(' ');
										cell.append(ddl);
										ddl.change(function (evnt) {
											var time = $(this).val();
											if (time != ' ') {
												var newDate = { Date: date, Title: time, URL: '#' };
												cell.data("active", 0);

												$.jMonthCalendar.AddEvents(newDate);
												// add new single event
											}
											ddl.remove();
										});
									}
								},
								data);
								ListOfPerfs = data;
							}
						);
		}
	}

	function ShowProdsGrid(datestr) {
		var gridimgpath = siteRoot + '/javascript/jQuery/jqGrid/themes/basic/images';

		$('#fragment-productions').html('<table  class="scroll" id="tblProductions"></table>');
		jQuery("#tblProductions").jqGrid({
			url: siteRoot + '/Admin/ProductionsJson.rails',
			postData: { TroupeID: $('#TroupeId').val(), Season: datestr },
			datatype: "json",
			colNames: ['Id', 'PlayId', 'VenueId', 'Title', 'At', 'From', 'To'],
			jsonReader: { repeatitems: false },
			colModel:
			[
				{ name: 'ProductionId', index: 'ProductionId', hidden: true, editable: false },
				{ name: 'PlayId', index: 'PlayId', hidden: true, editable: false },
				{ name: 'VenueId', index: 'VenueId', hidden: true, editable: false },
				{ name: 'Title', index: 'Title', width: 300, editable: false },
				{ name: 'name', index: 'name', width: 200, editable: false },
				{ name: 'FirstPerformance', index: 'FirstPerformance', width: 110, editable: false, datefmt: 'm/d/yyyy', sorttype: 'date' },
				{ name: 'LastPerformance', index: 'LastPerformance', width: 110, editable: false, datefmt: 'm/d/yyyy', sorttype: 'date' }
			],
			height: '200px',
			imgpath: gridimgpath,
			sortname: 'ProductionId',
			viewrecords: true,
			sortorder: "asc",
			caption: "Select production",
			onSelectRow: function (rowid) {
				var b = $("#tblProductions").getRowData(rowid);
				$('#ProductionId').val(b.ProductionId);
				$('#PlayId').val(b.PlayId);
				$('#txtPlay').val(b.Title);
				$('#FirstPerformance').val(b.FirstPerformance);
				$('#LastPerformance').val(b.LastPerformance);
				SelectVenueId(b.VenueId);
				$("#frmWizard").wizard("enableNext");
				$("#btnDeleteProd").enable();
				$("#btnAddCastlist1").enable();
				changed = false;
			}
		}).trigger("reloadGrid");
		$("#btnAddCastlist1").disable();
	}

	function SelectVenue(elm) {
		var vid = elm.val();
		SelectVenueId(vid);
		$("#frmWizard").wizard("enableNext");
	}
})

function SelectVenueId(vid) {
	j('#VenueId').val(vid);
	j('#venueInfo').load(siteRoot + '/Venue/Info.rails', { VenueId: vid });
}
